package com.ely.coupon.auth.handler;

import com.ely.coupon.auth.service.JwtService;
import com.ely.coupon.common.core.result.ResponseResult;
import com.ely.coupon.common.core.utils.ResponseUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功
 * 校验
 */
@Component
public class UserAuthSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    ObjectMapper objectMapper;
    @Resource
    JwtService jwtService;

    /**
     * JWT
     *
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //生成jwt
        User user = (User) authentication.getPrincipal();
        String token = jwtService.generateToken(user);
        ResponseUtils.responseToJson(httpServletResponse, objectMapper.writeValueAsString(ResponseResult.success(token)));
    }
}
